from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from user_operation.models import Address
from users.models import Users


class AddressSerializer(serializers.ModelSerializer):
    # 自动获取当前用户
    users = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Address
        fields = '__all__'

class UpdatePasswordSerializer(serializers.ModelSerializer):
    """
    修改密码序列化器
    """
    password = serializers.CharField(
        style={'input_type': 'password'}, help_text="密码", label="密码", write_only=True,
        min_length=6, max_length=16, required=True, error_messages={
            "blank": "请输入密码",
            "required": "请输入密码",
            "max_length": "密码太长应小于16位",
            "min_length": "密码太短应大于6位"
        }
    )

    re_password = serializers.CharField(
        style={'input_type': 'password'}, help_text="重复密码", label="重复密码", write_only=True,
        min_length=6, max_length=16, required=True, error_messages={
            "blank": "请再次输入密码",
            "required": "请再次输入密码",
            "max_length": "密码太长应小于16位",
            "min_length": "密码太短应大于6位"
        }
    )

    def validate(self, attrs):
        # 验证两次密码是否一致
        pwd = attrs.get('password')
        re_pwd = attrs.get('re_password')
        if pwd == re_pwd:
            del attrs['re_password']  # 可以在全局钩子移除模型中没有的属性
            return attrs
        else:
            raise ValidationError('两次输入密码不一样')

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Users
        fields = ('password', 're_password')